package com.ai.trickycards.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import com.ai.trickycards.databinding.ActivityWebviewBinding

class WebActivity : BaseActivity() {

    private val binding by lazy {
        ActivityWebviewBinding.inflate(layoutInflater)
    }

    companion object {
        fun open(
            context: Context,
            url: String,
            title: String
        ) {
            context.startActivity(Intent(context, WebActivity::class.java).apply {
                putExtra("url", url)
                putExtra("title", title)
            })
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setWindowInsets(binding.root)
        binding.ivClose.setOnClickListener { finish() }
        binding.webView.setBackgroundColor(0)
        binding.webView.background.alpha = 0
        binding.webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            databaseEnabled = true
        }

        binding.webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                // 注入自定义 CSS
                view.evaluateJavascript(
                    """
            var style = document.createElement('style');
            style.innerHTML = 'body { background-color: transparent; color: white; } a {color: white; }';
            document.head.appendChild(style);
        """.trimIndent(), null
                )
            }
        }

        intent.getStringExtra("url")?.let { url ->
            binding.webView.loadUrl(url)
        }
        binding.tvTitle.text = intent.getStringExtra("title")

    }

}